#include "ciowork.h"
#include <QtConcurrent/QtConcurrent>
#include <QDebug>

CIoWork::CIoWork(QObject *parent) :
    QObject(parent)
{
    m_serial.setPortName("/dev/ttyS0");
#if 0
    m_serial.setBaudRate(115200);
    m_serial.setParity(QSerialPort::NoParity);
    m_serial.setFlowControl(QSerialPort::NoFlowControl);
    m_serial.setDataBits(8);
    m_serial.setStopBits(1);
#endif
    m_serial.setBaudRate(4800);
    m_serial.setParity(QSerialPort::NoParity);
    m_serial.setFlowControl(QSerialPort::NoFlowControl);
    m_serial.setDataBits(8);
    m_serial.setStopBits(1);
    m_serial.open();

    if (!m_serial.isOpen()) return;

    m_readThread=QtConcurrent::run(CIoWork::readSerial, this);
}

CIoWork::~CIoWork() {
    m_serial.close();
}

void CIoWork::readSerial(CIoWork *io) {
    if (NULL == io) return;

    while(io->m_serial.isOpen()) {
        char szBuf[4096]={0};
        io->m_serial.read(szBuf, sizeof(szBuf)-1);
        qDebug() << "get data!!!!";
        io->m_readData.append(szBuf);
        emit io->sigDataChanged();
    }

}

QString CIoWork::read() {
    if (!m_serial.isOpen()) return "";
    m_readThread.pause();
    QString s=m_readData;
    m_readData.clear();
    m_readThread.resume();
    return s;
}

void CIoWork::write(QString szData) {
    if (!m_serial.isOpen()) return;

    QString szLine=szData;
    if (0 != szLine.right(1).compare("\n")) {
        m_writeCommand=szLine.mid(szLine.lastIndexOf("\n")+1);
        return;
    }
    else {
        m_writeCommand.append("\n");
    }
    m_serial.write(const_cast<char*>(m_writeCommand.toUtf8().constData()), m_writeCommand.length());
    m_writeCommand.clear();
}

void CIoWork::close() {
    if (m_serial.isOpen()) {
        write("\n");
        m_serial.close();
    }
    if (m_readThread.isRunning()) {
        m_readThread.waitForFinished();
    }
}
